let tabs;
let loginPage = "/login.html";

/**
 * 往localStorage中添加指定的tab
 * @param tab
 */
function addToTabs(tab) {
	if (!tabs) {
		tabs = [];
	}

	// 数组不存在才添加
	let exists = tabs.some(function (item) {
		return tab.title === item.title;
	});
	if (!exists) {
		tabs.push(tab);
	}

	setCurrent(tab.title);
	storage("tabs", JSON.stringify(tabs));
}

/**
 * 从localStorage中删除指定标题的tab
 * @param title
 */
function deleteFromTabs(title) {
	tabs = tabs.filter(function (item) {
		return item.title !== title;
	});

	storage("tabs", JSON.stringify(tabs));
}

/**
 * 获取所有打开的tab
 */
function getTabs() {
	let tabs = getStorage("tabs");

	return JSON.parse(tabs);
}

/**
 * 获取当前选中的tab
 */
function getCurrent() {
	return getStorage("currTab");
}

/**
 * 设置当前选中的tab
 */
function setCurrent(title) {
	storage("currTab", title);
}

/**
 * 初始化左侧菜单
 */
function InitLeftMenu() {
	$("#nav").accordion({
		animate: true
	});

	ajaxGet("/json/menus.json", {}, function(response) {
		$.each(response.data, function(i, node) {
			let menus = "<ul>";

			$.each(node.menus, function(j, child) {
				menus += "<li>";
				menus += 	"<div>";
				menus += 		"<a ref='" + child.id + "' href='javascript:void(0)' rel='" + child.url + "' >";
				menus += 			"<span class='icon " + child.icon + "' >&nbsp;</span>";
				menus += 			"<span class='nav'>" + child.name + "</span>";
				menus += 		"</a>";
				menus += 	"</div>";
				menus += "</li>";
			});

			menus += "</ul>";

			let $nav_ = $("#nav");

			$nav_.accordion("add", {
				title: node.name,
				content: menus,
				iconCls: "icon " + node.icon
			});

			//选中第一个tab
			let panels = $nav_.accordion("panels");
			let tab = panels[0].panel("options").title;

			$nav_.accordion("select", tab);
		});

		$(".easyui-accordion li a").on("click", function() {
			let url = $(this).attr("rel");
			let title = $(this).children(".nav").text();
			let icon = $(this).children(".icon").attr("class");

			addTab(title, url, icon);

			$(".easyui-accordion li div").removeClass("selected");
			$(this).parent().addClass("selected");
		}).hover(function() {
			$(this).parent().addClass("hover");
		}, function() {
			$(this).parent().removeClass("hover");
		});
	}, error);
}

function addTab(title, url, icon = "") {
	let $tabs_ = $("#tabs");
	let exists = $tabs_.tabs("exists", title);

	if (!exists) {
		$tabs_.tabs("add", {
			title: title,
			icon: icon,
			closable: true,
			content: createFrame(url)
		});

		addToTabs({
			title: title,
			url: url
		});
	} else {
		$tabs_.tabs("select", title);
		$("#mm-tabupdate").click();
	}

	tabClose();
}

function createFrame(url) {
	return "<iframe style='width:100%;height:98%;' scrolling='auto' frameborder='0'  src='" + url + "'></iframe>";
}

function tabClose() {
	// 为选项卡绑定右键
	$(".tabs-inner").bind("contextmenu", function(e) {
		e.preventDefault();

		$("#right-menu").menu("show", {
			left: e.pageX,
			top: e.pageY
		});

		let title = $(this).children(".tabs-closable").text();

		setCurrent(title);

		$("#tabs").tabs("select", title);
	}).dblclick(function() { // 双击关闭TAB选项卡
		let currTab = $(this).children(".tabs-closable").text();

		$("#tabs").tabs("close", currTab);

		deleteFromTabs(currTab);
	});
}

/**
 * 绑定右键菜单事件
 */
function tabCloseEven() {
	let _tabs = $("#tabs");

	// 刷新
	$("#mm-tabupdate").click(function() {
		let currTab = _tabs.tabs("getSelected");
		let url = $(currTab.panel("options").content).attr("src");

		_tabs.tabs("update", {
			tab: currTab,
			options: {
				content: createFrame(url)
			}
		})
	});

	// 关闭当前
	$("#mm-tabclose").click(function() {
		let title = getCurrent();

		deleteFromTabs(title);
		_tabs.tabs("close", title);
	});

	// 全部关闭
	$("#mm-tabcloseall").click(function() {
		$(".tabs-inner > span.tabs-closable").each(function(i, n) {
			let title = $(n).text();

			deleteFromTabs(title);
			_tabs.tabs("close", title);
		});
	});

	// 关闭除当前之外的TAB
	$("#mm-tabcloseother").click(function() {
		$("#mm-tabcloseright").click();
		$("#mm-tabcloseleft").click();
	});

	// 关闭当前左侧的TAB
	$("#mm-tabcloseleft").click(function() {
		let prevAll = $(".tabs-selected").prevAll();

		if(prevAll.length > 0) {
			prevAll.each(function(i, n) {
				let title = $("span.tabs-inner:eq(0) span.tabs-closable", $(n)).text();

				deleteFromTabs(title);
				_tabs.tabs("close", title);
			});
		}
	});

	// 关闭当前右侧的TAB
	$("#mm-tabcloseright").click(function() {
		let nextAll = $(".tabs-selected").nextAll();

		if(nextAll.length > 0) {
			nextAll.each(function(i, n) {
				let title = $("span.tabs-inner:eq(0) span.tabs-closable", $(n)).text();

				deleteFromTabs(title);
				_tabs.tabs("close", title);
			});
		}
	});
}

$(function() {
	InitLeftMenu();
	tabClose();
	tabCloseEven();

	ajaxGet("/user/getLogin", {}, function(response) {
		let data = response.data;

		$("#loginName").html(data.name);
	}, error);

	$("#tabs").tabs("add", {
		title: "欢迎使用",
		icon: "",
		closable: false,
		content: createFrame("/main.html")
	});

	/******************************************************************************************************/

	$("#more").menubutton({
		menu: "#menu"
	});

	$("#clean").on("click", function() {
		ajaxPost("/cache/clean", {},function(response) {
			showMsg(response.message);

			localStorage.clear();
		}, error);
	});

	// 安全退出
	$("#logout").click(function() {
		$.messager.confirm("系统提示", "您确定要退出本次登录吗?", function(bool) {
			if (bool) {
				ajaxPost("/user/logout", {}, function() {
					location.href = loginPage;
				}, error);
			}
		});
	});

	/******************************************************************************************************/

	let _tabs = $("#tabs");

	_tabs.tabs({
		fit: true,
		border: false,
		onClose: function(title) {
			deleteFromTabs(title);
		},
		onSelect: function(title) {
			setCurrent(title);
			console.log("切换当前标签页：" + title);

			let currTab = _tabs.tabs("getTab", title);
			let iframe = $(currTab.panel("options").content);
			let src = iframe.attr("src");

			if (src) {
				_tabs.tabs("update", {
					tab: currTab,
					options: {
						content: createFrame(src)
					}
				});
			}
		}
	});

	// 还原tab
	tabs = getTabs();

	if (tabs && tabs.length > 0) {
		// 还原当前tab
		let currTab = getCurrent();

		for (let i = 0; i < tabs.length; i++) {
			let tab = tabs[i];

			addTab(tab.title, tab.url);
		}

		if (currTab) {
			_tabs.tabs("select", currTab);

			console.log("恢复当前标签页：" + currTab);
		}
	}

});